const express = require('express')
const multer = require('multer')
const boom = require('boom')
const { UPLOAD_PATH } = require('../utils/constant')
const Result = require('../models/Result')
const { rename, dirExists } = require('./utils')
// const {md5 , decode} = require('../utils')
const editer = require('../service/user')

const router = express.Router()



router.get('/list',function(req, res, next){
  Promise.resolve().then( () => {
    // console.log(list);
    new Result({name:1,password:2},'获取图书列表成功').success(res)
  }).catch(err => {
    next(boom.badImplementation(err))
  })
})

router.post('/testpost',function(req, res, next){
  console.log(req);
  Promise.resolve().then( () => {
    // console.log(list);
    // next(boom.badImplementation('err11'))
    new Result({name:1,password:2},'获取图书列表成功').success(res)
  }).catch(err => {
    next(boom.badImplementation(err))
  })
})


router.post('/img', multer({dest:`./assets/img/${new Date().getDate()}/`}).any(),async function(req, res, next){
  const img = req.files
  console.log(img);
  // console.log(req.body);
  const oldpath = process.cwd()+'/'+img[0].path
  const suffix = `.${img[0].originalname.split('.')[1]}`
  // 可能出现multer文件还没保存完成，出现路径不存在
  // console.log('-----------------------');
  // console.log(process.cwd()+`/assets/img/${new Date().getDate()}`);
  // await dirExists(process.cwd()+`/assets/img/${new Date().getDate()}`)
  // new Result({ url:123 },'图片上传成功').success(res)
  rename(oldpath, oldpath+suffix)
    .then(()=>{
      const url = `http://localhost:3000/${img[0].path}${suffix}`
      new Result({ url },'图片上传成功').success(res)
    })
    .catch(err => {
      next(boom.badImplementation('图片上传失败'))
    })
})

router.post('/html', multer({dest:`./assets/html/${new Date().getDate()}/`}).any(),async function(req, res, next){
  const img = req.files
  console.log(img);
  console.log(req.body);
  const oldpath = process.cwd()+'/'+img[0].path
  const suffix = `.${img[0].mimetype.split('/')[1]}`
  rename(oldpath, oldpath+suffix)
    .then(async ()=>{
      const url = `http://localhost:3000/${img[0].path}${suffix}`
      await editer.updateTemplate({
        ...req.body,
        url
      })
      new Result({ url },'网页上传成功').success(res)
    })
    .catch(err => {
      next(boom.badImplementation('网页上传失败'))
    })
})

router.get('/templatelist', async function(req, res, next) {
  try {
    // const {
    //   table,
    //   title,
    //   userID,
    //   order
    // } = query
    // await wait(2000)
    let list = await editer.getTemplaList(req.query)
    console.log('-------');
    console.log(list);
    new Result({ list },'获取列表信息成功').success(res)
  } catch(err) {
    next(boom.badImplementation(err))
  }
})
// id  
router.get('/removeTem', async function(req, res, next) {
  try {
    await editer.removeTem(
     req.query.id, req.query.type
    )
    new Result({ },'成功删除').success(res)
  } catch(err) {
    next(boom.badImplementation(err))
  }
})
function wait(ms) {
  return new Promise(resolve => setTimeout(() =>resolve(), ms));
};
// pageId,from...
router.get('/template2page', async function(req, res, next) {
  try {
    // req.query.from = '123456'
    // req.query.pageId = 'snakeman'
    const template = await editer.exitstsTemplate({ templateId: req.query.from})
    console.log(template);
    if(template){
      await editer.insertTemplate({ ...template, pageId: req.query.pageId})
      new Result({  },'成功创建').success(res)
    } else {
      new Result({  },'模板不存在').success(res)
    }
  } catch(err) {
    next(boom.badImplementation(err))
  }
})

router.get('/template', async function(req, res, next) {
  try {
    // let r = await editer.getTemplaList({
    //   table: 'template',
    //   order: 'createTime'
    // })
    // console.log('-------');
    // console.log(r);
    console.log(req.query);
    const result = await editer.exitstsTemplate(req.query)
    if(result && result.backupData) {
      result.backupData = JSON.parse(result.backupData)
    }
    new Result({ result },'获取模板信息').success(res)
  } catch(err) {
    next(boom.badImplementation(err))
  }
})

router.post('/template', async function(req, res, next) {
  try {
    const cover =  JSON.parse(req.body.backupData).title
    console.log(cover);
    await editer.updateTemplate({...req.body,cover, userID:req.headers['x-token'].split('.')[0]})
    new Result({ },'模板信息保存成功').success(res)
  } catch(err) {
    next(boom.badImplementation(err))
  }
})

router.post('/login', async function(req, res, next) {
  try {
    let result = await editer.exitstsUser(req.body)
    console.log('11111');
    console.log(result);
    if(!result){
      new Result({},'账户不存在').fail(res)
    } else if(result.password !== req.body.password){
      new Result({},'密码错误').fail(res)
    } else {
      new Result(result,'登陆成功').success(res)
    } 
  } catch(err) {
    next(boom.badImplementation(err))
  }
})

router.post('/register', async function(req, res, next) {
  try {
    let result = await editer.exitstsUser(req.body)
    if(result){
      new Result({},'账户已存在').fail(res)
    } else {
      await editer.insertUser(req.body)
      new Result(result,'注册成功,登陆成功').success(res)
    } 
  } catch(err) {
    next(boom.badImplementation(err))
  }
})


module.exports = router